package cn.springcloud.alibaba.auth.service;

import cn.springcloud.alibaba.auth.dao.entity.SysUser;
import cn.springcloud.alibaba.auth.dao.mapper.SysUserMapper;
import cn.springcloud.alibaba.security.vo.UserInfo;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Set;

@Slf4j
@Service
public class MyUserDetailsService implements UserDetailsService {

	@Autowired
	private SysUserMapper sysUserMapper;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		SysUser sysUser = sysUserMapper.selectOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getUserName, username));
		if (sysUser == null) {
			throw new UsernameNotFoundException("账户不存在！");
		}
		return this.assembleUserDetail(sysUser);
	}

	private UserInfo assembleUserDetail(SysUser sysUser) {
		Set<GrantedAuthority> authorities = new HashSet<>();
		String[] roleCodes = sysUser.getRoleCode().split(",");
		for (String roleCode : roleCodes) {
			authorities.add(new SimpleGrantedAuthority(roleCode));
		}
		UserInfo userInfo = new UserInfo();
		userInfo.setId(sysUser.getId());
		userInfo.setPassword(sysUser.getPassword());
		userInfo.setUsername(sysUser.getUserName());
		userInfo.setAuthorities(authorities);
		return userInfo;
	}
}
